﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Security;
using TinyForum.Web.Proxies.ServiceReference;
using System.Collections.Specialized;
using TinyForum.Infrastructure;

namespace TinyForum.Web.Extensions.Mvc
{
    public class TinyForumMembershipProvider : MembershipProvider
    {
        private string applicationName;
        private bool enablePasswordReset;
        private bool enablePasswordRetrieval = false;
        private bool requiresQuestionAndAnswer = false;
        private bool requiresUniqueEmail = true;
        private int maxInvalidPasswordAttempts;
        private int passwordAttemptWindow;
        private int minRequiredPasswordLength;
        private int minRequiredNonalphanumericCharacters;
        private string passwordStrengthRegularExpression;
        private MembershipPasswordFormat passwordFormat = MembershipPasswordFormat.Encrypted;

        private MembershipUser ConvertFrom(AccountDataObject accountData)
        {
            if (accountData == null)
                return null;
            MembershipUser user = new MembershipUser(this.Name,
                accountData.UserName, accountData.ID, accountData.Email, accountData.PasswordQuestion,
                "", accountData.IsApproved, accountData.IsLocked, accountData.DateJoined,
                accountData.DateLastLogon ?? DateTime.MinValue,
                DateTime.MinValue,
                accountData.DateLastPasswordChanged ?? DateTime.MinValue,
                accountData.DateLastLocked ?? DateTime.MinValue);
            return user;
        }

        private string GetValue(string configValue, string defaultValue)
        {
            if (string.IsNullOrEmpty(configValue))
                return defaultValue;

            return configValue;
        }

        public override string ApplicationName
        {
            get
            {
                return applicationName;
            }
            set
            {
                applicationName = value;
            }
        }

        public override string Name
        {
            get
            {
                return "TinyForumMembershipProvider";
            }
        }

        public override string Description
        {
            get
            {
                return "Membership Provider for TinyForum";
            }
        }

        public override void Initialize(string name, NameValueCollection config)
        {
            if (config == null)
                throw new ArgumentNullException("config");

            if (name == null || name.Length == 0)
                name = "TinyForumMembershipProvider";

            if (String.IsNullOrEmpty(config["description"]))
            {
                config.Remove("description");
                config.Add("description", this.Description);
            }

            base.Initialize(name, config);

            applicationName = GetValue(config["applicationName"], System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath);
            maxInvalidPasswordAttempts = Convert.ToInt32(GetValue(config["maxInvalidPasswordAttempts"], "5"));
            passwordAttemptWindow = Convert.ToInt32(GetValue(config["passwordAttemptWindow"], "10"));
            minRequiredNonalphanumericCharacters = Convert.ToInt32(GetValue(config["minRequiredNonalphanumericCharacters"], "1"));
            minRequiredPasswordLength = Convert.ToInt32(GetValue(config["minRequiredPasswordLength"], "6"));
            enablePasswordReset = Convert.ToBoolean(GetValue(config["enablePasswordReset"], "true"));
            passwordStrengthRegularExpression = Convert.ToString(GetValue(config["passwordStrengthRegularExpression"], ""));
        }

        public override bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            using (AccountApplicationClient accountApplicationClient = new AccountApplicationClient())
            {
                return accountApplicationClient.ChangePassword(username, oldPassword, newPassword);
            }
        }

        public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
        {
            using (AccountApplicationClient accountApplicationClient = new AccountApplicationClient())
            {
                return accountApplicationClient.ChangePasswordQuestionAndAnswer(username, password, newPasswordQuestion, newPasswordAnswer);
            }
        }

        public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
        {
            ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(username, password, true);
            OnValidatingPassword(args);
            if (args.Cancel)
            {
                status = MembershipCreateStatus.InvalidPassword;
                return null;
            }
            if (RequiresUniqueEmail && !string.IsNullOrEmpty(GetUserNameByEmail(email)))
            {
                status = MembershipCreateStatus.DuplicateEmail;
                return null;
            }
            using (AccountApplicationClient accountApplicationClient = new AccountApplicationClient())
            {
                var accountExists = accountApplicationClient.AccountExists(username);
                if (accountExists)
                {
                    status = MembershipCreateStatus.DuplicateUserName;
                    return null;
                }
                else
                {
                    AccountDataObject accountDataObject = new AccountDataObject
                    {
                        DateJoined = DateTime.Now,
                        Email = email,
                        IsAdmin = false,
                        IsLocked = false,
                        IsApproved = isApproved,
                        DisplayName = username,
                        Password = password,
                        PasswordAnswer = passwordAnswer,
                        PasswordQuestion = passwordQuestion,
                        UserName = username,
                    };
                    long ID = accountApplicationClient.Register(accountDataObject);
                    accountDataObject.ID = ID;
                    status = MembershipCreateStatus.Success;
                    return ConvertFrom(accountDataObject);
                }
            }
        }

        public override bool DeleteUser(string username, bool deleteAllRelatedData)
        {
            throw new NotImplementedException();
        }

        public override bool EnablePasswordReset
        {
            get { return this.enablePasswordReset; }
        }

        public override bool EnablePasswordRetrieval
        {
            get { return this.enablePasswordRetrieval; }
        }

        public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            using (AccountApplicationClient accountApplicationClient = new AccountApplicationClient())
            {
                MembershipUserCollection collection = new MembershipUserCollection();
                var accounts = accountApplicationClient.GetAccountsByEmail(emailToMatch);
                if (accounts != null)
                {
                    totalRecords = accounts.Length;
                    accounts.ToList().ForEach(ac => collection.Add(ConvertFrom(ac)));
                    return collection;
                }
                else
                {
                    totalRecords = 0;
                    return null;
                }
            }
        }

        public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            using (AccountApplicationClient accountApplicationClient = new AccountApplicationClient())
            {
                MembershipUserCollection collection = new MembershipUserCollection();
                var accounts = accountApplicationClient.GetAccountsByUserName(usernameToMatch);
                if (accounts != null)
                {
                    totalRecords = accounts.Length;
                    accounts.ToList().ForEach(ac => collection.Add(ConvertFrom(ac)));
                    return collection;
                }
                else
                {
                    totalRecords = 0;
                    return null;
                }
            }
        }

        public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
        {
            using (AccountApplicationClient accountApplicationClient = new AccountApplicationClient())
            {
                MembershipUserCollection collection = new MembershipUserCollection();
                var accounts = accountApplicationClient.GetAllAccounts();
                if (accounts != null)
                {
                    totalRecords = accounts.Length;
                    accounts.ToList().ForEach(ac => collection.Add(ConvertFrom(ac)));
                    return collection;
                }
                else
                {
                    totalRecords = 0;
                    return null;
                }
            }
        }

        public override int GetNumberOfUsersOnline()
        {
            throw new NotImplementedException();
        }

        public override string GetPassword(string username, string answer)
        {
            using (AccountApplicationClient accountApplicationClient = new AccountApplicationClient())
            {
                return accountApplicationClient.GetPassword(username, answer);
            }
        }

        public override MembershipUser GetUser(string username, bool userIsOnline)
        {
            using (AccountApplicationClient accountApplicationClient = new AccountApplicationClient())
            {
                var accounts = accountApplicationClient.GetAccountsByUserName(username);
                if (accounts != null && accounts.Length > 0)
                    return ConvertFrom(accounts[0]);
                return null;
            }
        }

        public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
        {
            using (AccountApplicationClient accountApplicationClient = new AccountApplicationClient())
            {
                var account = accountApplicationClient.GetAccount(Convert.ToInt64(providerUserKey));
                return ConvertFrom(account);
            }
        }

        public override string GetUserNameByEmail(string email)
        {
            using (AccountApplicationClient accountApplicationClient = new AccountApplicationClient())
            {
                var accounts = accountApplicationClient.GetAccountsByEmail(email);
                if (accounts != null && accounts.Length > 0)
                    return accounts[0].UserName;
                return null;
            }
        }

        public override int MaxInvalidPasswordAttempts
        {
            get { return this.maxInvalidPasswordAttempts; }
        }

        public override int MinRequiredNonAlphanumericCharacters
        {
            get { return this.minRequiredNonalphanumericCharacters; }
        }

        public override int MinRequiredPasswordLength
        {
            get { return this.minRequiredPasswordLength; }
        }

        public override int PasswordAttemptWindow
        {
            get { return this.passwordAttemptWindow; }
        }

        public override MembershipPasswordFormat PasswordFormat
        {
            get { return this.passwordFormat; }
        }

        public override string PasswordStrengthRegularExpression
        {
            get { return this.passwordStrengthRegularExpression; }
        }

        public override bool RequiresQuestionAndAnswer
        {
            get { return this.requiresQuestionAndAnswer; }
        }

        public override bool RequiresUniqueEmail
        {
            get { return requiresUniqueEmail; }
        }

        public override string ResetPassword(string username, string answer)
        {
            using (AccountApplicationClient accountApplicationClient = new AccountApplicationClient())
            {
                return accountApplicationClient.ResetPassword(username, answer);
            }
        }

        public override bool UnlockUser(string userName)
        {
            using (AccountApplicationClient accountApplicationClient = new AccountApplicationClient())
            {
                accountApplicationClient.Unlock(userName);
                return true;
            }
        }

        public override void UpdateUser(MembershipUser user)
        {
            throw new NotImplementedException();
        }

        public override bool ValidateUser(string username, string password)
        {
            using (AccountApplicationClient userApplicationClient = new AccountApplicationClient())
            {
                return userApplicationClient.Authenticate(username, password);
            }
        }
    }
}
